package flect.study;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Mytest {
    @Test
    public void getReflectClass() throws ClassNotFoundException {
        // 获取Class对象的三种方式
        Class c1 = Class.forName("flect.study.Student");
        Class c2 = Student.class;
        Class c3 = new Student().getClass();

        System.out.println(c1);
        System.out.println(c2);
        System.out.println(c3);

    }

    @Test
    public void getReflectConstructor() throws Exception {
        // 首先要获取Class对象
        Class c = Class.forName("flect.study.Student");
        // 获取构造方法 全部获取
        Constructor[] constructors = c.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }

        // 获取构造方法 指定参数类型
        Constructor constructor1 = c.getDeclaredConstructor(String.class);
        Constructor constructor2 = c.getDeclaredConstructor(String.class, int.class);
        Constructor constructor3 = c.getDeclaredConstructor(String.class, int.class, String.class);

        System.out.println(constructor1);
        System.out.println(constructor2);
        System.out.println(constructor3);

        // 使用构造方法创建对象
        // 因为私有，所以需要设置 accessible 为 true
        constructor1.setAccessible(true);
        Student newInstance = (Student)constructor1.newInstance("张三");
        System.out.println(newInstance);
    }

    @Test
    public void getReflectFiled() throws Exception {
        // 首先要获取Class对象
        Class c = Class.forName("flect.study.Student");
        Constructor constructor = c.getDeclaredConstructor(String.class, int.class);
        Object obj = constructor.newInstance("张三", 18);
        // 获取所有属性
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field);
        }

        // 获取指定属性名称的属性
        Field field = c.getDeclaredField("age");
        // 获取属性的值
        field.setAccessible(true);
        System.out.println(field.get(obj));
        // 设置属性的值
        field.set(obj,20);
        System.out.println(field.get(obj));
    }

    @Test
    public void getReflectMethod() throws Exception {
        // 首先要获取Class对象
        Class c = Class.forName("flect.study.Student");
        Constructor constructor = c.getDeclaredConstructor(String.class, int.class);
        Object obj = constructor.newInstance("张三", 18);
        // 获取指定方法名称的方法
        Method method = c.getDeclaredMethod("eat");
        method.setAccessible(true);
        method.invoke(obj);

        // 获取所有方法
        Method[] methods = c.getDeclaredMethods();
        for (Method method1 : methods) {
            System.out.println(method1);
        }
    }
}